<template>
  <div class="app-container">
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row> -->

    <el-table v-loading="loading" :data="tableData" border>
      <el-table-column label="学校" align="center" prop="merchantName" />
      <el-table-column label="入住时间" align="center" prop="createTime" />

      <el-table-column label="管理" align="center" width="300">
        <template slot-scope="scope">
          <el-button size="mini" plain type="primary" @click="handleEnter(scope.row)">进入</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer :visible.sync="drawer" direction="rtl" size="70%">
      <el-button type="primary" size="mini" style="margin-left: 30px;" @click="addEquip">新增设备分组</el-button>
      <el-button type="primary" size="mini" @click="downLoad">下载模板</el-button>
      <div style="margin-left: 30px;margin-top: 10px;margin-right: 30px;">
        <el-table v-loading="loading" :data="equipData" border size="mini">
          <el-table-column label="学校" align="center" prop="merchantName" />
          <el-table-column label="设备类型" align="center" prop="type" />
          <el-table-column label="管理" align="center" width="240">
            <template slot-scope="scope">
              <div style="display: flex;justify-content: space-around;">
                <el-button size="mini" plain type="primary" @click="showInsert(scope.row)">单设备录入</el-button>
                <!-- <el-button size="mini" plain type="primary" @click="">批量录入</el-button> -->
                <el-upload action="#" :before-upload="beforeUpload" ref="newupload" :show-file-list="false"
                  :http-request="uploadHttpRequestIn" :limit="3" :file-list="fileList">
                  <el-button size="mini" type="primary" plain icon="el-icon-upload2"
                    @click="upload(scope.row)">批量录入</el-button>
                </el-upload>
                <!-- <el-button size="mini" plain type="primary" >设备移除</el-button> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column label="设备详情" align="center" width="160">
            <template slot-scope="scope">
              <el-button size="mini" plain type="primary" @click="lookDetail(scope.row)">查看</el-button>
              <el-button size="mini" plain type="primary" @click="exportEquip(scope.row)">导出</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
    </el-drawer>

    <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="" /> -->

    <!-- 新增设备分组对话框 -->
    <el-dialog title="新增设备分组" :visible.sync="open" width="500px" append-to-body style="margin-top:50px;">
      <el-form ref="form" :model="form" label-width="150px">
        <el-form-item label="学校名称">
          <el-input v-model="form.merchantName" disabled clearable style="width:240px;" />
        </el-form-item>
        <!-- <el-form-item label="设备分组">
          <el-input v-model="form.equipGroup" placeholder="请输入设备分组名称" clearable style="width:240px;" />
        </el-form-item> -->
        <el-form-item label="设备类型">
          <el-select v-model="form.type" placeholder="请选择设备类型" clearable style="width:240px;">
            <el-option v-for="item in Selection" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addEquipConfirm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 设备信息录入对话框 -->
    <el-dialog title="设备信息录入" :visible.sync="openIn" width="500px" append-to-body style="margin-top:50px;">
      <el-form :model="formIn" label-width="150px">
        <el-form-item label="设备编号">
          <el-input v-model="formIn.code" placeholder="请输入设备编号" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="formIn.name" placeholder="请输入设备名称" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="formIn.model" placeholder="请输入设备型号" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="formIn.value" placeholder="请选择设备类型" clearable style="width:240px;">
            <el-option v-for="item in Selection" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertEquip">确 定</el-button>
        <el-button @click="openIn = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备修改对话框 -->
    <el-dialog title="设备信息修改" :visible.sync="openChange" width="500px" append-to-body style="margin-top:50px;">
      <el-form :model="formChange" label-width="150px">
        <el-form-item label="设备编号">
          <el-input v-model="formChange.code" placeholder="请输入设备编号" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="formChange.name" placeholder="请输入设备名称" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="formChange.model" placeholder="请输入设备型号" clearable style="width:240px;" />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select v-model="formChange.value" placeholder="请选择设备类型" clearable style="width:240px;">
            <el-option v-for="item in Selection" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertEquip">确 定</el-button>
        <el-button @click="openChange = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看设备信息对话框 -->
    <el-dialog title="设备信息" :visible.sync="openInfo" append-to-body width="700px" style="margin-top:20px;">
      <div class="dialog-top">
        <el-button type="danger" plain icon="el-icon-delete" @click="removeEquip">设备移除</el-button>
        <el-button type="primary" plain icon="el-icon-s-order">设备总数量： {{ number }}</el-button>
      </div>
      <el-table :data="dataInfo" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="code" label="设备编号" align="center"></el-table-column>
        <el-table-column prop="name" label="设备名称" align="center"></el-table-column>
        <el-table-column prop="model" label="设备型号" align="center"></el-table-column>
        <el-table-column prop="type" label="设备类型" align="center"></el-table-column>
        <el-table-column prop="status" label="设备状态" align="center"></el-table-column>
        <el-table-column label="设备管理" align="center">
          <!-- <template slot-scope="scope">
            <el-button size="mini" plain type="primary" >修改</el-button>
          </template> -->
        </el-table-column>
      </el-table>
      <el-pagination class="paginationIn" background layout="total, sizes, prev, pager, next, jumper" :total="totalDetail"
        :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChangeDetail"
        @size-change="handleSizeChangeDetail"></el-pagination>
    </el-dialog>


  </div>
</template>

<script>
import {
  getEquipInfo,
  getEquipForm,
  getSelection,
  addEquipConfirm,
  lookDetail,
  downLoad,
  insertEquip,
  exportEquip,
  removeEquip,
  importData
} from "@/api/equipmentCenter/index.js";

export default {
  name: "Notice",
  data() {
    return {
      openIn: false,
      drawer: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      // 设备数据
      equipData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openBind: false,
      openInfo: false,
      infoData: [],
      // 列表查询参数
      queryParams: {
        current: 0,
        pageSize: 10
      },
      //进入学校
      enterInfo: {
        current: 0,
        pageSize: 10,
        merchantId: ""
      },
      //设备类型下拉框
      Selection: [],
      // 新增设备表单参数
      form: {
        // equipGroup: "",
        merchantId: "",
        merchantName: "",
        type: ""
      },
      // 设备录入表单参数
      formIn: {
        code: "",
        equipGroupId: "",
        merchantId: "",
        model: "",
        name: "",
        type: "",
        value: ""
      },
      //查看设备表单参数
      equipInfo: {
        current: 0,
        groupId: "",
        merchantId: "",
        pageSize: 10
      },
      totalDetail: "",
      // // 表单校验
      // rules: {
      //   groupName: [
      //     { required: true, message: "营业分组不能为空", trigger: "blur" }
      //   ],
      //   modelName: [
      //     { required: true, message: "运营模式不能为空", trigger: "change" }
      //   ]
      // },

      //设备数量
      number: "",
      //设备详情
      dataInfo: [],
      timeNow: "",
      fileList: [],
      fileData: {
        groupId: "",
        merchantId: ""
      },
      multipleSelection: []
    };
  },
  created() {
    this.getList();

  },
  methods: {
    // 设备移除
    removeEquip() {
      removeEquip(this.multipleSelection).then(res => {
        if (res.data.success == true) {
          this.$message.success(res.data.message)
          lookDetail(this.equipInfo).then(res => {
            // console.log(res);
            if (res.data.success == true) {
              this.number = res.data.data.count
              this.dataInfo = res.data.data.list.list;
              this.totalDetail = res.data.data.list.total;
            } else {
              this.$message.info(res.data.message)
            }
          })
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    handleSelectionChange(val) {
      // console.log(val);
      val.forEach(item => {
        if (!this.multipleSelection.includes(item.code)) {
          this.multipleSelection.push(item.code)
        }
      })
      if (val.length == 0) {
        this.multipleSelection = []
      }
      console.log(this.multipleSelection);

    },
    //进入学校弹窗分页
    handleCurrentChange(e) {
      this.enterInfo.current = e - 1
      getEquipForm(this.enterInfo).then(res => {
        if (res.data.success == true) {
          this.equipData = res.data.data.list;
          this.total = res.data.data.total;
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    //进入学校弹窗分页
    handleSizeChange(e) {
      this.enterInfo.pageSize = e
      getEquipForm(this.enterInfo).then(res => {
        if (res.data.success == true) {
          this.equipData = res.data.data.list;
          this.total = res.data.data.total;
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    //设备信息弹窗分页
    handleCurrentChangeDetail(e) {
      this.equipInfo.current = e - 1
      lookDetail(this.equipInfo).then(res => {
        // console.log(res);
        if (res.data.success == true) {
          this.number = res.data.data.count
          this.dataInfo = res.data.data.list.list;
          this.totalDetail = res.data.data.list.total;
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    //设备信息弹窗分页
    handleSizeChangeDetail(e) {
      this.equipInfo.pageSize = e
      lookDetail(this.equipInfo).then(res => {
        // console.log(res);
        if (res.data.success == true) {
          this.number = res.data.data.count
          this.dataInfo = res.data.data.list.list;
          this.totalDetail = res.data.data.list.total;
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    beforeUpload(file) {
      // console.log(file)
      // 校验
      let legalName = ["xlsx", "xls"];
      // 拿到后缀名
      let name = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      if (legalName.includes(name)) {
        // console.log(legalName.includes(name));
      } else {
        this.$message.info("文件格式不对,仅限xls和xlsx");
        return false;
      }
    },
    upload(e) {
      console.log(e);
      this.fileData.groupId = e.groupId
      this.fileData.merchantId = e.merchantId
    },
    // 批量录入设备信息
    uploadHttpRequestIn(data) {
      console.log(data)
      let fd = new FormData()
      fd.append('file', data.file)
      // groupId:this.fileData.groupId,
      // merchantId:this.fileData.merchantId
      importData({
        fd,
        groupId: this.fileData.groupId,
        merchantId: this.fileData.merchantId
      }).then(res => {
        if (res.data.success == true) {
          this.$message.success("录入成功！")
          // this.$router.go(0)
        } else {
          this.$message.info(res.data.message)
        }
      })
    },

    /** 查询列表 */
    getList() {
      getEquipInfo(this.queryParams).then(res => {
        if (res.data.success == true) {
          this.tableData = res.data.data.list;
          this.total = res.data.data.total;
          // this.loading = false;
        } else {
          this.$message.info(res.data.message)
        }
      }).catch(error => {
        console.log(error.response.status);
        if (error.response.status == 401) {
          this.$confirm('登录状态过期, 请重新登录!', '提示', {
            confirmButtonText: '确定',
            // cancelButtonText: '取消',
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
            this.$router.push('/login')
          }).catch(() => {

          })
        }
      })
    },
    //进入学校详情
    handleEnter(e) {
      this.drawer = true;
      this.enterInfo.merchantId = e.merchantId;
      this.form.merchantId = e.merchantId;
      this.form.merchantName = e.merchantName
      getEquipForm(this.enterInfo).then(res => {
        if (res.data.success == true) {
          this.equipData = res.data.data.list;
          this.total = res.data.data.total;
          // this.loading = false;
        } else {
          this.$message.info(res.data.message)
        }

      })
      getSelection().then(res => {
        if (res.data.data) {
          this.Selection = res.data.data
        }
      })
    },
    //新增弹窗
    addEquip() {
      this.open = true
    },
    //新增确认
    addEquipConfirm() {
      addEquipConfirm(this.form).then(res => {
        if (res.data.success == true) {
          this.open = false
          this.$message({
            message: '添加成功!',
            duration: 1000,
            type: 'success',
            onClose: () => {
              this.form.equipGroup = ""
              this.form.type = ""
              // this.$router.go(0)
              // this.resetQuery()
              getEquipForm(this.enterInfo).then(res => {
                if (res.data.success == true) {
                  this.equipData = res.data.data.list;
                  this.total = res.data.data.total;
                  // this.loading = false;
                } else {
                  this.$message.info(res.data.message)
                }
              })
            }
          })
        }
      })
    },
    // 设备录入弹窗
    showInsert(e) {
      this.openIn = true
      this.formIn.equipGroupId = e.groupId
      this.formIn.merchantId = e.merchantId
      this.formIn.code = ""
      this.formIn.name = ""
      this.formIn.model = ""
      this.formIn.value = ""
    },
    // 设备录入
    insertEquip() {
      insertEquip(this.formIn).then(res => {
        if (res.data.success == true) {
          this.openIn = false
          this.$message({
            message: '录入成功!',
            duration: 1000,
            type: 'success',
            onClose: () => {

            }
          })
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    //查看设备详情
    lookDetail(e) {
      this.dataInfo = ""
      this.openInfo = true
      this.equipInfo.merchantId = e.merchantId
      this.equipInfo.groupId = e.groupId
      lookDetail(this.equipInfo).then(res => {
        // console.log(res);
        if (res.data.success == true) {
          this.number = res.data.data.count
          this.dataInfo = res.data.data.list.list;
          this.totalDetail = res.data.data.list.total;
        } else {
          this.$message.info(res.data.message)
        }
      })
    },
    // 下载模板
    downLoad() {
      downLoad().then(res => {
        // console.log(res, "121212121212")
        const link = document.createElement('a')  //创建a标签
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
        link.style.display = 'none'// 设置连接
        link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
        this.getCurrentTime()
        link.download = '设备信息模板_' + this.timeNow
        document.body.appendChild(link) // 模拟点击事件
        link.click()  //设置点击事件
        this.$message.success('下载成功！')
      })
    },
    //导出表单文件
    exportEquip(e) {
      exportEquip({
        groupId: e.groupId,
        merchantId: e.merchantId
      }).then(res => {
        // console.log(res, "121212121212")
        const link = document.createElement('a')  //创建a标签
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
        link.style.display = 'none'// 设置连接
        link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
        this.getCurrentTime()
        link.download = '设备信息_' + this.timeNow
        document.body.appendChild(link) // 模拟点击事件
        link.click()  //设置点击事件
        this.$message.success('下载成功！')
      })
    },
    //获取当前时间
    getCurrentTime() {
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss;
      // console.log(_this.gettime)
      this.timeNow = _this.gettime
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: "0"
      };
      this.resetForm("form");
    },

    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.noticeId)
    //   this.single = selection.length != 1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "新增营业分组";
      this.form = {
        groupName: "",
        modelName: ""
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true;
      this.title = "修改营业分组";
      console.log(row);
      this.form.groupName = row.groupName
      this.form.modelName = row.modelName
      this.form.groupId = row.id
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.groupName == "") {
        this.$message('营业分组不能为空！')
        return false
      }
      if (this.form.modelName == "") {
        this.$message('运营模式不能为空！')
        return false
      }
      if (this.title == "新增营业分组") {
        // 添加
        addGroup(this.form).then(res => {
          // console.log(res)
          if (res.status == 200) {
            this.open = false
            this.$message({
              message: '添加成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.$router.go(0)
              }
            })
          }
        })
      } else {
        updateGroup(this.form).then(res => {
          // console.log(res)
          if (res.status == 200) {
            this.open = false
            this.$message({
              message: '修改成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.$router.go(0)
              }
            })
          }
        })
      }

    },
    /** 绑定按钮操作 */
    handleBind(row) {
      this.openBind = true
    },
    //查看设备数量
    getNumber() {
      groupNum(this.groupId).then(res => {
        // console.log(res);
        this.number = res.data.data
      })
    },
    //查看设备详情
    getInfo() {
      this.openInfo = true
      groupInfo(this.groupId).then(res => {
        // this.groupId = ""
        // console.log(res);
        if (res.data.success == true) {
          if (res.data.data) {
            this.dataInfo = res.data.data
          }
        } else {
          this.$message(res.data.message)
        }
      }).catch(error => {
        // console.log(error.response);
        console.log(error.response.status);
        if (error.response.status != 200) {
          this.$message(error.response.data.message)
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('此操作将删除该营业分组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeGroup(row.id).then(res => {
          console.log(res)
          if (res.status == 200) {
            this.$message({
              message: '删除成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.$router.go(0)
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
};
</script>

<style>
.dialog-top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.pagination {
  float: right;
  margin-top: 10px;
  margin-right: 40px;
}

.paginationIn {
  margin-top: 10px;
  margin-left: 200px;
}</style>
